/**
 * publish - compile posts to static html and rss
 */

define('publish', ['app', 'element', 'os', 'shell'], function (app, element, os, shell) {
    'use strict';
    
    var shell = new shell.Shell(document.body),
        template = new os.File('/template.html'),
        i;
    
    function publish(m) {
        // stop with error if index.html could not be read
        if (m.hasOwnProperty('error')) {
            shell.print(m);
            return;
        }
        
        // get list of posts
        os.listdir('/posts/', function (files) {
            var content = {},
                read = files.length,
                post,
                dateString,
                full_content,
                brief_content,
                title,
                permalink,
                html_posts = '',
                rss_items = '';
            
            files.sort();
            
            shell.print('');
            shell.print('compiling ' + read + ' posts');
            
            for (i = 0; i < files.length; i++) {
                post = files[i];
                element.create('div', {parent:document.body, attr:{'class': 'post', 'id': '/posts/' + post}});
                new os.File('/posts/' + post).read(function(result) {
                    content[result.success.path] = result.success.content;
                    if (!--read) {
                        while (post = files.pop()) {
                            dateString = post.slice(0, post.indexOf('.'));
                            full_content = content['/posts/' + post];
                            title = full_content.replace(/[\s\S]*<h2>(.*)<\/h2>[^$]*/im, '$1');
                            permalink = '/post/' + title.replace(/[,\-'\[\]\(\):&]*/igm, '').replace(/[ ]+/igm, '_').toLowerCase() + '.html';
                            brief_content = full_content;
                            if (brief_content.length > 500) {
                                brief_content = brief_content.slice(0, 500);
                                if (brief_content.lastIndexOf('>') < brief_content.lastIndexOf('<')) {
                                    brief_content = brief_content.slice(0, brief_content.lastIndexOf('<') - 1);
                                }
                                brief_content = brief_content + '...</a></p>';
                            }
                            html_posts += html_post(brief_content, dateString, permalink, 'briefpost');
                            write_html(html_post(full_content, dateString, permalink, 'fullpost'), false, permalink);
                            rss_items += rss_item(title, brief_content, dateString);
                        }
                        
                        // write rss
                        var rss = new os.File('/rss.xml');
                        rss.write('<rss version="2.0">\n');
                        rss.write('  <channel>\n');
                        rss.write('    <title>Tribsloft</title>\n');
                        rss.write('    <link>http://tribsloft.appspot.com/</link>\n');
                        rss.write('    <description>Tribsloft | Posts from Tribs</description>\n');
                        rss.write('    <language>en-au</language>\n');
                        rss.write('    ' + rss_items);
                        rss.write('  </channel>\n');
                        rss.write('</rss>\n');
                        rss.close(function(m) {
                            if (m.hasOwnProperty('error')) {
                                shell.print(m);
                            } else if (m.hasOwnProperty('success')) {
                                shell.print(m.success.path + ' written');
                            }
                        });
                        
                        // write index.html
                        write_html(html_posts, true, '/index.html');
                    }
                });
            }
        });
    }
    
    
    function html_post(content, dateString, permalink, postclass) {
        var post = '';
        post    += '        <div class="' + postclass + '">\n';
        post    += content;
        post    += '          <span class="permalink"><a href="' + permalink + '">permalink</a></span>\n';
        post    += '        </div>\n';
        return post;
    }
    
    
    function rss_item(content, dateString) {
        var item = '  <item>\n';
        item    += '    <title>' + content.replace(/.*<h2>(.*)<\/h2>[^$]*/im, '$1') + '</title>\n';
        item    += '    <link>http://tribsloft.appspot.com/post/' + dateString + '.html</link>\n';
        item    += '    <description>' + content.replace(/^(.*<\/h2>)?(.*)/g, '$2') + '</description>\n';
        item    += '    <pubDate>' + new Date(dateString).toUTCString() + '</pubDate>\n';
        item    += '  </item>\n';
        return item;
    }
    
    
    function write_html(posts, labs, path, fn) {
        var file = new os.File(path);
        
        file.write(template.content.replace(/<!--POSTS-->/igm, '<div id="posts">\n' + posts + '</div>'));
        
        if (!labs) {
            file.content = file.content.replace(
                /<!--LABS\/-->[\s\S]*<!--\/LABS-->/igm, '');
        }
        
        file.close(function(m) {
            if (m.hasOwnProperty('error')) {
                shell.print(m);
            } else if (m.hasOwnProperty('success')) {
                shell.print(path + ' written');
            }
        });
    }
    
    // main application
    if (app.main === 'publish') {
        os.identity(document.location, function(m) {
            if (m.hasOwnProperty('login')) {
                document.location = m.login;
            }
            os.environ.user = m;
            document.title = 'publish - ' + window.location.hostname;
            shell.print(document.title);
            shell.print('logged in as ' + os.environ.user.name);
            shell.print();
            template.read(publish);
        });
    }
});
